#!/usr/bin/env python3
import csv
import requests
import os
import time
from urllib.parse import urlparse
from dotenv import load_dotenv

def get_repo_info(url):
    """从GitHub URL中提取owner和repo名称"""
    path = urlparse(url).path.strip('/')
    if path.endswith('.git'):
        path = path[:-4]
    return path.split('/')[-2:]

def create_gitee_repo(access_token, repo_name, description=""):
    """在Gitee上创建仓库"""
    url = "https://gitee.com/api/v5/user/repos"
    headers = {"Content-Type": "application/json"}
    params = {
        "access_token": access_token,
        "name": repo_name,
        "description": description,
        "private": False,
        "auto_init": False
    }
    
    response = requests.post(url, headers=headers, params=params)
    return response.status_code == 201

def import_github_to_gitee(access_token, gitee_owner, github_url):
    """从GitHub导入仓库到Gitee"""
    base_api_url = "https://gitee.com/api/v5/repos/migrate"
    headers = {"Content-Type": "application/json;charset=UTF-8"}

    github_repo_owner, repo_name = get_repo_info(github_url)

    payload = {
        "repo_name": repo_name,
        "source_url": github_url,
        "gitee_username": gitee_owner,
    }

    query_params = {
        "access_token": access_token
    }

    response_message = "未知错误"

    try:
        response = requests.post(base_api_url, headers=headers, params=query_params, json=payload)
        
        if response.status_code == 201:
            return True, repo_name, "导入请求已成功提交"
        else:
            error_detail = response.text
            try:
                error_json = response.json()
                response_message = error_json.get("message", response.text)
                if "errors" in error_json:
                    response_message += f" Details: {error_json['errors']}"
            except ValueError:
                response_message = response.text
            
            detailed_error_msg = f"导入失败 (状态码: {response.status_code}): {response_message}"
            print(detailed_error_msg)
            return False, repo_name, detailed_error_msg
            
    except requests.exceptions.RequestException as e:
        detailed_error_msg = f"请求异常: {str(e)}"
        print(detailed_error_msg)
        return False, repo_name, detailed_error_msg

def main():
    # 加载 .env 文件中的环境变量
    load_dotenv()

    # 从环境变量或用户输入获取Gitee配置
    # 注意：.env 文件中的变量名是 gitee_token, gitee_org, gitee_user
    access_token = os.getenv('gitee_token')
    if not access_token:
        access_token = input("请输入Gitee访问令牌: ").strip()

    # 优先使用组织名，其次是用户名
    gitee_owner = os.getenv('gitee_org')
    if not gitee_owner:
        gitee_owner = os.getenv('gitee_user')
    
    if not gitee_owner:
        gitee_owner = input("请输入Gitee用户名或组织名: ").strip()
    
    # 创建日志文件
    log_file = "gitee_import.log"
    success_count = 0
    fail_count = 0
    
    # 确保CSV文件路径正确
    csv_file_path = '/root/ws/2025/04/agiros_pkg_build_tools/git_urls.csv'
    if not os.path.exists(csv_file_path):
        print(f"错误: CSV文件未找到于 {csv_file_path}")
        return

    with open(csv_file_path, 'r', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        for row in reader:
            url = row['URL']
            if not url.startswith('https://github.com'):
                print(f"跳过非GitHub仓库: {url}")
                with open(log_file, 'a', encoding='utf-8') as log:
                    log.write(f"跳过 (非GitHub): {url}\n")
                continue
                
            print(f"\n处理仓库: {url}")
            success, repo_name, message = import_github_to_gitee(access_token, gitee_owner, url)
            
            with open(log_file, 'a', encoding='utf-8') as log:
                if success:
                    success_count += 1
                    log_entry = f"成功提交导入请求: {url} -> gitee.com/{gitee_owner}/{repo_name} - Gitee消息: {message}\n"
                    log.write(log_entry)
                    print(f"导入请求已成功提交: gitee.com/{gitee_owner}/{repo_name}")
                else:
                    fail_count += 1
                    log_entry = f"失败: {url} - 原因: {message}\n"
                    log.write(log_entry)
            
            time.sleep(2)
    
    print(f"\n处理完成:")
    print(f"成功提交导入请求数: {success_count}")
    print(f"失败数: {fail_count}")
    print(f"详细日志已写入: {log_file}")

if __name__ == "__main__":
    main()